package com.aim.config.origin;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 多数据源处理
 */
@Aspect
@Order(-10)
@Component
public class DynamicDataSourceAspect {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Pointcut("@annotation(com.aim.config.origin.MultiDataSource)")
    public void dsPointCut() {
    }

    @Around("dsPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        if (!(signature instanceof MethodSignature)) {
            throw new IllegalArgumentException("该注解只能用于方法");
        } else {
            Method method = signature.getMethod();
            MultiDataSource dataSource = method.getAnnotation(MultiDataSource.class);
            if (null != dataSource) {
                DynamicContextHolder.setDateSoureType(dataSource.value().name());
            }
            try {
                return point.proceed();
            } finally {
                // 销毁数据源 在执行方法之后
                DynamicContextHolder.clearDateSoureType();
            }
        }
    }
}
